package common.businesslog;

import com.alibaba.fastjson.JSONObject;
import common.dateutils.AsyncFlowDateUtil;
import common.http.AsyncFlowHttpClientUtil;
import common.sendmsg.AsyncFlowSendMsg;
import models.*;
import org.apache.commons.lang.StringUtils;

import java.util.Comparator;
import java.util.stream.Collectors;

/**
 * 业务日志
 */
public class SaveBusinessLog {
    /**
     * 添加业务日志
     */
    public static <TAsyncContext> void saveBusinessLog(AsyncFlowRequest request, AsyncFlowData<TAsyncContext> asyncFlowData, String msg, boolean allNodeIsSuccess) {
        try {

            StringBuilder stringBuilder = new StringBuilder();
            String reason = "";
            if (!allNodeIsSuccess) {
                reason = "失败原因：" + msg;
                AsyncFlowBusinessLog.addBusinessLog(asyncFlowData, reason, true);
            }
            if (asyncFlowData.getAsyncBusinessLogEntityList().isEmpty()) {
                return;
            }

            if (StringUtils.isBlank(request.getBusinessSerialId())) {
                return;
            }
            String logInfo = "【" + request.getSourceDes() + "】触发【" + request.getAsyncFlowNodeEnum().getMsg() + "】【" + (allNodeIsSuccess ? "成功" : "失败") + "】";

            for (AsyncFlowBusinessLogEntity orderLogEntity : asyncFlowData.getAsyncBusinessLogEntityList().stream().sorted(Comparator.comparing(AsyncFlowBusinessLogEntity::getLocalDateTime)).collect(Collectors.toList())) {
                //在失败的情况下，仅仅记录必须要记录的日志（非必须的不记录-跳过）
                if (!allNodeIsSuccess && !orderLogEntity.isMustRecord()) {
                    continue;
                }
                stringBuilder.append(orderLogEntity.getLogInfo()).append("<Br/>");
            }
            String log = stringBuilder.toString() + logInfo;
            AsyncFlowSaveBusinessLogEntity saveBusinessLogEntity = new AsyncFlowSaveBusinessLogEntity();
            saveBusinessLogEntity.setBusinessSerialId(request.getBusinessSerialId());
            if (StringUtils.isBlank(request.getOperateName())) {
                request.setOperateName("0");
            }
            if (StringUtils.isBlank(request.getOperateNo())) {
                request.setOperateNo("0");
            }
            saveBusinessLogEntity.setOperateName(request.getOperateName());
            saveBusinessLogEntity.setOperateNo(request.getOperateNo());
            saveBusinessLogEntity.setLogInfo(log);
            saveBusinessLogEntity.setLogTime(AsyncFlowDateUtil.htFormatyyyyMMddHHmm(request.getRequesterTime()));
            String result = AsyncFlowHttpClientUtil.post(asyncFlowData.getAsyncFlowInfo().getBusinessLogUrl(), JSONObject.toJSONString(saveBusinessLogEntity));
            JSONObject jsonObject = JSONObject.parseObject(result);
            int code = jsonObject.getShort("Code");
            if (code != 200) {
                String errorMsg = jsonObject.getString("Msg");
                AsyncFlowSendMsg.sendAlarmMsg(request, errorMsg, "保存业务日志", asyncFlowData.getAsyncFlowInfo());
            }
        } catch (Exception e) {
            String s = AsyncFlowSendMsg.buildErrorMsg(request, e, "保存业务日志", asyncFlowData.getAsyncFlowInfo());
            AsyncFlowSendMsg.SendQYWXMsg(asyncFlowData.getAsyncFlowInfo().getFlowMaintainName(), s, asyncFlowData.getAsyncFlowInfo().getNodeArmUrl());
        }


    }


}
